import { Card, Table, Modal, Form, Input, Tag, Space, Row, Col, Typography, Statistic, Descriptions, Badge, Tabs, Divider, message, Upload, Button, Select, Spin, Popconfirm } from '@/utils/antd-imports';
import { CheckOutlined, FileTextOutlined, MoneyCollectOutlined, SearchOutlined, HourglassOutlined, CloseCircleOutlined, UploadOutlined, SwapOutlined, UserDeleteOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { projectApi } from '@/api/projectApi';
import { acceptanceMemberApi, projectAcceptanceApi } from '@/api/projectAcceptanceApi';
import employeeApi from '@/api/employeeApi';











import DatePicker from 'antd/es/date-picker';








import InputNumber from 'antd/es/input-number';

import moment from 'moment';
import InvoiceTab from './InvoiceTab';
import PaymentTab from './PaymentTab';

const { Text, Title } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

const ProjectSettlementForm = ({ projectId, projectCode, projectName }) => {
  const [settlements, setSettlements] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 新增状态
  const [employees, setEmployees] = useState([]);
  const [loadingEmployees, setLoadingEmployees] = useState(false);

  // 加载验收单数据
  useEffect(() => {
    loadAcceptances();
  }, [projectCode]);

  const loadAcceptances = async () => {
    if (!projectCode) return;
    
    setLoading(true);
    try {
      const response = await projectApi.getAcceptancesByProjectCode(projectCode);
      if (response.code === 200) {
        const acceptances = response.data || [];
        // 将验收单数据转换为结算数据格式
        const transformedSettlements = acceptances.map(acceptance => ({
          id: acceptance.id,
          settlementNo: acceptance.acceptanceNo,
          projectId: acceptance.projectId,
          projectCode: acceptance.projectCode,
          projectName: acceptance.projectName,
          subProjectName: acceptance.subProjectName,
          contactPerson: acceptance.contactPerson,
          client: acceptance.client,
          department: acceptance.department,
          section: acceptance.section,
          contractNo: acceptance.contractNo,
          budgetAmount: acceptance.budgetAmount,
          acceptanceAmount: acceptance.acceptanceAmount,
          totalHours: acceptance.totalHours,
          acceptanceDate: acceptance.acceptanceDate,
          priority: acceptance.priority,
          startDate: acceptance.startDate,
          endDate: acceptance.endDate,
          workType: acceptance.workType,
          acceptancePersonId: acceptance.acceptancePersonId,
          acceptancePersonName: acceptance.acceptancePersonName,
          acceptanceStandard: acceptance.acceptanceStandard,
          acceptanceStatus: acceptance.status === '已验收' ? 'accepted' : acceptance.status === '待验收' ? 'not_accepted' : 'in_progress',
          acceptanceCompletionTime: acceptance.acceptanceCompletionTime,
          attachmentUrls: acceptance.attachmentUrls,
          remark: acceptance.remark,
          staffs: [] // 验收成员通过单独的API加载
        }));
        setSettlements(transformedSettlements);
      } else {
        message.error(response.message || '加载验收单失败');
      }
    } catch (error) {
      console.error('加载验收单失败:', error);
      message.error('加载验收单失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载员工数据
  const loadEmployees = async () => {
    try {
      setLoadingEmployees(true);
      const response = await employeeApi.getAllActiveEmployees();
      if (response.code === 200 && response.data) {
        setEmployees(response.data);
      }
    } catch (error) {
      console.error('加载员工数据失败:', error);
    } finally {
      setLoadingEmployees(false);
    }
  };

  // 搜索员工
  const handleEmployeeSearch = async (searchText) => {
    if (!searchText) {
      setEmployeeSearchResults([]);
      return;
    }
    
    try {
      setLoadingEmployees(true);
      const response = await employeeApi.searchEmployees(searchText);
      if (response.code === 200 && response.data) {
        setEmployeeSearchResults(response.data);
      }
    } catch (error) {
      console.error('搜索员工失败:', error);
    } finally {
      setLoadingEmployees(false);
    }
  };

  // 组件挂载时加载员工数据
  useEffect(() => {
    loadEmployees();
    loadProjectCards();
  }, []);
  
  // 加载项目卡片列表
  const loadProjectCards = async () => {
    try {
      const response = await projectApi.getProjectCards();
      if (response.code === 200) {
        setProjectCards(response.data || []);
      }
    } catch (error) {
      console.error('加载项目卡片失败:', error);
    }
  };
  
  // 根据项目编号获取子项目列表
  const loadSubProjectsByProjectCode = async (projectCode) => {
    if (!projectCode) {
      setTransferSubProjects([]);
      return;
    }
    try {
      const response = await projectApi.getSubProjectsByProjectCode(projectCode);
      if (response.code === 200) {
        setTransferSubProjects(response.data || []);
      }
    } catch (error) {
      console.error('加载子项目失败:', error);
      message.error('加载子项目失败');
    }
  };
  
  // 处理项目编号变化
  const handleProjectCodeChange = (projectCode) => {
    setTransferProjectCode(projectCode);
    setTransferSubProjectId('');
    loadSubProjectsByProjectCode(projectCode);
  };
  
  // 处理离项
  const handleLeaveProject = async (member) => {
    try {
      // 调用API更新验收成员状态
      const response = await acceptanceMemberApi.updateMemberStatus(member.id, '离项审核中');
      if (response.code === 200) {
        // 如果经营范围中有合同人员ID，也需要更新合同人员状态
        if (member.contractPersonnelId) {
          // TODO: 调用合同人员API更新状态
          // const contractResponse = await contractPersonnelApi.updateStatus(member.contractPersonnelId, '离项审核中');
        }
        
        message.success('离项申请已提交');
        
        // 刷新验收成员列表
        const membersResponse = await acceptanceMemberApi.getMembersByAcceptance(currentRecord.id);
        if (membersResponse.code === 200) {
          setAcceptanceMembers(membersResponse.data || []);
        }
      } else {
        message.error(response.message || '离项申请失败');
      }
    } catch (error) {
      console.error('离项申请失败:', error);
      message.error('离项申请失败');
    }
  };
  
  // 处理转项
  const handleTransferProject = async (member) => {
    setCurrentTransferMember(member);
    setTransferVisible(true);
    transferForm.resetFields();
  };
  
  // 提交转项
  const submitTransfer = async () => {
    try {
      const values = await transferForm.validateFields();
      
      // 调用API更新验收成员信息
      const response = await acceptanceMemberApi.transferMember(currentTransferMember.id, {
        newProjectCode: values.projectCode,
        newSubProjectId: values.subProjectId
      });
      
      if (response.code === 200) {
        message.success('转项成功');
        setTransferVisible(false);
        transferForm.resetFields();
        
        // 刷新验收成员列表
        const membersResponse = await acceptanceMemberApi.getMembersByAcceptance(currentRecord.id);
        if (membersResponse.code === 200) {
          setAcceptanceMembers(membersResponse.data || []);
        }
      } else {
        message.error(response.message || '转项失败');
      }
    } catch (error) {
      console.error('转项失败:', error);
      if (error.errorFields) {
        return;
      }
      message.error('转项失败');
    }
  };

  // 状态选项
  const statusOptions = [
    { label: '已完成', value: 'completed' },
    { label: '部分支付', value: 'partial' },
    { label: '待结算', value: 'pending' },
    { label: '已取消', value: 'cancelled' }
  ];

  // 验收状态选项
  const acceptanceStatusOptions = [
    { label: '未验收', value: 'not_accepted' },
    { label: '已验收', value: 'accepted' }
  ];

  // 单价类型选项
  const priceTypeOptions = [
    { label: '时', value: 'hour' },
    { label: '天', value: 'day' },
    { label: '月', value: 'month' }
  ];

  // 表单状态
  const [form] = Form.useForm();
  const [acceptanceVisible, setAcceptanceVisible] = useState(false);
  const [contractVisible, setContractVisible] = useState(false);
  const [membersModalVisible, setMembersModalVisible] = useState(false);
  const [acceptanceMembers, setAcceptanceMembers] = useState([]);
  const [loadingMembers, setLoadingMembers] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('acceptance');
  const [activeAcceptanceStatus, setActiveAcceptanceStatus] = useState('all'); // all, accepted, not_accepted
  const [fileList, setFileList] = useState([]);
  const [priceType, setPriceType] = useState('hour');
  const [actualEndDate, setActualEndDate] = useState(null);
  
  // 员工搜索相关状态
  const [employeeSearchValue, setEmployeeSearchValue] = useState('');
  const [employeeSearchResults, setEmployeeSearchResults] = useState([]);
  
  // 转项相关状态
  const [transferVisible, setTransferVisible] = useState(false);
  const [transferProjectCode, setTransferProjectCode] = useState('');
  const [transferSubProjectId, setTransferSubProjectId] = useState('');
  const [transferSubProjects, setTransferSubProjects] = useState([]);
  const [projectCards, setProjectCards] = useState([]);
  const [currentTransferMember, setCurrentTransferMember] = useState(null);
  const [transferForm] = Form.useForm();

  // 处理验收 - 显示验收成员
  const handleAcceptance = async (record) => {
    setCurrentRecord(record);
    setAcceptanceVisible(true);
    
    // 加载验收成员数据
    if (record.id) {
      setLoadingMembers(true);
      try {
        const response = await acceptanceMemberApi.getMembersByAcceptance(record.id);
        if (response.code === 200) {
          setAcceptanceMembers(response.data || []);
          // 设置默认单价类型
          if (response.data && response.data.length > 0) {
            setPriceType(response.data[0].priceType || 'hour');
          }
        } else {
          message.error('加载验收成员失败');
        }
      } catch (error) {
        console.error('加载验收成员失败:', error);
        message.error('加载验收成员失败');
      } finally {
        setLoadingMembers(false);
      }
    }
    
    setActualEndDate(record.actualEndDate || new Date().toISOString().split('T')[0]);
  };

  // 查看验收详情
  const handleViewDetail = async (record) => {
    setCurrentRecord(record);
    setAcceptanceVisible(true);
    
    // 加载验收成员数据
    if (record.id) {
      setLoadingMembers(true);
      try {
        const response = await acceptanceMemberApi.getMembersByAcceptance(record.id);
        if (response.code === 200) {
          setAcceptanceMembers(response.data || []);
          // 设置默认单价类型
          if (response.data && response.data.length > 0) {
            setPriceType(response.data[0].priceType || 'hour');
          }
        } else {
          message.error('加载验收成员失败');
        }
      } catch (error) {
        console.error('加载验收成员失败:', error);
        message.error('加载验收成员失败');
      } finally {
        setLoadingMembers(false);
      }
    }
  };

  // 计算结算金额
  const calculateSettlementAmount = (unitPrice, actualHours, type) => {
    if (!actualHours || !unitPrice) return 0;
    switch (type) {
      case 'hour':
        return unitPrice * actualHours;
      case 'day':
        return unitPrice * actualHours;
      case 'month':
        return unitPrice;
      default:
        return 0;
    }
  };

  // 处理员工切换
  const handleEmployeeChange = async (memberId, employeeId) => {
    if (!employeeId) return;
    
    const employee = employees.find(emp => emp.id === employeeId);
    if (!employee) return;
    
    const updatedMembers = acceptanceMembers.map(member => {
      if (member.id === memberId) {
        return {
          ...member,
          employeeId: employee.id,
          employeeName: employee.name,
          employeeCode: employee.employeeCode || null
        };
      }
      return member;
    });
    
    setAcceptanceMembers(updatedMembers);
  };

  // 处理实际工时变化
  const handleActualHoursChange = (memberId, value) => {
    const updatedMembers = acceptanceMembers.map(member => {
      if (member.id === memberId) {
        const actualHours = value || 0;
        const settlementAmount = calculateSettlementAmount(
          member.unitPrice, 
          actualHours, 
          member.priceType
        );
        return {
          ...member,
          actualHours,
          settlementAmount
        };
      }
      return member;
    });
    
    setAcceptanceMembers(updatedMembers);
  };

  // 处理单价类型变化
  const handlePriceTypeChange = (value) => {
    setPriceType(value);
    
    // 同时更新验收成员列表的单价类型和重新计算金额
    const updatedMembers = acceptanceMembers.map(member => ({
      ...member,
      priceType: value,
      settlementAmount: calculateSettlementAmount(
        member.unitPrice, 
        member.actualHours || 0, 
        value
      )
    }));
    setAcceptanceMembers(updatedMembers);
  };

  // 提交验收
  const submitAcceptance = async () => {
    // 检查所有人员的实际工时是否已填写
    const hasEmptyHours = acceptanceMembers.some(member => 
      member.actualHours === null || member.actualHours === undefined || member.actualHours === 0
    );
    
    if (hasEmptyHours) {
      message.error('请填写所有人员的实际工时');
      return;
    }

    const totalAmount = acceptanceMembers.reduce((sum, member) => sum + (member.settlementAmount || 0), 0);
    const totalActualHours = acceptanceMembers.reduce((sum, member) => sum + (member.actualHours || 0), 0);

    try {
      setLoadingMembers(true);
      
      // 1. 更新所有验收成员的实际工时和结算金额
      const updatePromises = acceptanceMembers.map(member => 
        acceptanceMemberApi.updateMember(member.id, {
          actualHours: member.actualHours,
          settlementAmount: member.settlementAmount,
          priceType: member.priceType,
          employeeId: member.employeeId,
          employeeName: member.employeeName,
          employeeCode: member.employeeCode
        })
      );
      
      await Promise.all(updatePromises);
      
      // 2. 更新验收单状态和金额
      const acceptanceUpdateData = {
        actualEndDate: actualEndDate,
        acceptanceAmount: totalAmount,
        totalHours: totalActualHours,  // 添加总工时
        workType: priceType,  // 添加工时类型
        status: '已验收',
        acceptanceCompletionTime: new Date().toISOString()
      };
      
      const updateResponse = await projectAcceptanceApi.updateAcceptance(
        currentRecord.id, 
        acceptanceUpdateData
      );
      
      if (updateResponse.code !== 200) {
        throw new Error(updateResponse.message || '更新验收单失败');
      }
      
      message.success('验收成功');
      setAcceptanceVisible(false);
      form.resetFields();
      setFileList([]);
      
      // 重新加载验收单列表
      loadAcceptances();
      
    } catch (error) {
      console.error('验收失败:', error);
      message.error(error.message || '验收失败，请重试');
    } finally {
      setLoadingMembers(false);
    }
  };

  // 查看合同详情
  const viewContract = (record) => {
    setCurrentRecord(record);
    setContractVisible(true);
  };

  // 过滤结算列表
  const filteredSettlements = settlements.filter(settlement => {
    // 先按验收状态过滤
    if (activeAcceptanceStatus !== 'all') {
      if (activeAcceptanceStatus === 'accepted' && settlement.acceptanceStatus !== 'accepted') {
        return false;
      }
      if (activeAcceptanceStatus === 'not_accepted' && settlement.acceptanceStatus === 'accepted') {
        return false;
      }
    }
    
    // 再按搜索文本过滤
    if (!searchText) return true;
    const searchLower = searchText.toLowerCase();
    return (
      settlement.settlementNo?.toLowerCase().includes(searchLower) ||
      settlement.projectName?.toLowerCase().includes(searchLower) ||
      settlement.subProjectName?.toLowerCase().includes(searchLower) ||
      settlement.contractNo?.toLowerCase().includes(searchLower)
    );
  });

  // 根据当前页签获取统计数据
  const getStatisticsByTab = () => {
    const now = new Date();
    const overdueAcceptance = settlements.filter(s => 
      s.acceptanceStatus === 'not_accepted' && 
      s.estimatedEndDate && 
      new Date(s.estimatedEndDate) < now
    ).length;

    switch (activeTab) {
      case 'acceptance':
        const acceptedCount = settlements.filter(s => s.acceptanceStatus === 'accepted').length;
        const notAcceptedCount = settlements.filter(s => s.acceptanceStatus === 'not_accepted').length;
        // 如果没有验收单或全部是待验收，显示未验收状态
        const allNotAccepted = settlements.length === 0 || notAcceptedCount === settlements.length;
        
        return {
          total: settlements.length,
          completed: acceptedCount,
          pending: notAcceptedCount,
          overdue: overdueAcceptance,
          amount: settlements.reduce((sum, s) => sum + (s.budgetAmount || s.acceptanceAmount || 0), 0),
          completedAmount: settlements
            .filter(s => s.acceptanceStatus === 'accepted')
            .reduce((sum, s) => sum + (s.acceptanceAmount || 0), 0)
        };
      case 'invoice':
        return {
          total: settlements.length,
          completed: settlements.filter(s => s.invoiceStatus === 'invoiced').length,
          pending: settlements.filter(s => s.invoiceStatus === 'not_invoiced').length,
          amount: settlements.reduce((sum, s) => sum + (s.budgetAmount || s.acceptanceAmount || 0), 0),
          completedAmount: settlements
            .filter(s => s.invoiceStatus === 'invoiced')
            .reduce((sum, s) => sum + (s.invoiceAmount || 0), 0)
        };
      case 'payment':
        return {
          total: settlements.length,
          completed: settlements.filter(s => s.paymentStatus === 'paid').length,
          partial: settlements.filter(s => s.paymentStatus === 'partial_paid').length,
          pending: settlements.filter(s => s.paymentStatus === 'unpaid').length,
          amount: settlements.reduce((sum, s) => sum + (s.budgetAmount || s.acceptanceAmount || 0), 0),
          paidAmount: settlements.reduce((sum, s) => sum + (s.paidAmount || 0), 0),
          remainingAmount: settlements.reduce((sum, s) => sum + (s.remainingAmount || 0), 0)
        };
      default:
        return {};
    }
  };

  const stats = getStatisticsByTab();

  // 表格列定义
  const acceptanceColumns = [
    {
      title: '验收编号',
      dataIndex: 'settlementNo',
      key: 'settlementNo',
      width: 150,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 150
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 150
    },
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
      width: 150
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100
    },
    {
      title: '客户',
      dataIndex: 'client',
      key: 'client',
      width: 120
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '科室',
      dataIndex: 'section',
      key: 'section',
      width: 100
    },
    {
      title: '合同号/呈批号',
      dataIndex: 'contractNo',
      key: 'contractNo',
      width: 150,
      render: (text) => (
        <a onClick={() => viewContract(text)}>{text}</a>
      )
    },
    {
      title: '预算金额',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 120,
      render: (amount) => (
        <Text>¥{amount?.toLocaleString() || '-'}</Text>
      )
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '总工时',
      dataIndex: 'totalHours',
      key: 'totalHours',
      width: 100,
      render: (hours) => (
        <Text strong>{hours !== null && hours !== undefined ? hours.toLocaleString() : '-'}</Text>
      )
    },
    {
      title: '工时类型',
      dataIndex: 'workType',
      key: 'workType',
      width: 100,
      render: (type) => {
        const typeMap = { 'hour': '时', 'day': '天', 'month': '月' };
        return typeMap[type] || type || '-';
      }
    },
    {
      title: '验收金额',
      dataIndex: 'acceptanceAmount',
      key: 'acceptanceAmount',
      width: 120,
      render: (amount) => (
        <Text strong>¥{amount?.toLocaleString() || '-'}</Text>
      )
    },
    {
      title: '验收时间点',
      dataIndex: 'acceptanceDate',
      key: 'acceptanceDate',
      width: 120,
      render: (date) => date || '-'
    },
    {
      title: '已验收时间',
      dataIndex: 'acceptanceCompletionTime',
      key: 'acceptanceCompletionTime',
      width: 120,
      render: (date) => {
        if (date) {
          if (typeof date === 'string') {
            return date.split('T')[0];
          }
          return new Date(date).toISOString().split('T')[0];
        }
        return '-';
      }
    },
    {
      title: '验收状态',
      dataIndex: 'acceptanceStatus',
      key: 'acceptanceStatus',
      width: 120,
      render: (status) => {
        const isAccepted = status === 'accepted';
        return (
          <Tag color={isAccepted ? 'green' : 'orange'} icon={isAccepted ? <CheckOutlined /> : <HourglassOutlined />}>
            {acceptanceStatusOptions.find(s => s.value === status)?.label || status}
          </Tag>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => {
        if (record.acceptanceStatus === 'not_accepted') {
          return <a onClick={() => handleAcceptance(record)}>验收</a>;
        } else if (record.acceptanceStatus === 'accepted') {
          return <a onClick={() => handleViewDetail(record)}>详情</a>;
        }
        return null;
      }
    }
  ];

  // 处理文件上传
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 人员表格列定义
  const staffColumns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <Text>{text}</Text>
    },
    {
      title: '岗位名称',
      dataIndex: 'jobTitle',
      key: 'jobTitle'
    },
    {
      title: '人员编号',
      dataIndex: 'staffNo',
      key: 'staffNo'
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      render: (price, record) => (
        <InputNumber 
          min={0}
          value={price}
          onChange={(value) => handleUnitPriceChange(record.id, value)}
          style={{ width: '100%' }}
          formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
          parser={value => value.replace(/¥\s?|(,*)/g, '')}
        />
      )
    },
    {
      title: '单价类型',
      dataIndex: 'priceType',
      key: 'priceType',
      render: (type) => priceTypeOptions.find(opt => opt.value === type)?.label
    },
    {
      title: '实际工时',
      dataIndex: 'actualHours',
      key: 'actualHours',
      render: (hours, record) => (
        <InputNumber 
          min={0}
          value={hours}
          onChange={(value) => handleActualHoursChange(record.id, value)}
          style={{ width: '100%' }}
        />
      )
    },
    {
      title: '结算金额',
      dataIndex: 'settlementAmount',
      key: 'settlementAmount',
      render: (amount) => (
        <Text strong>¥{amount?.toLocaleString() || '-'}</Text>
      )
    }
  ];

  return (
    <div style={{ padding: '24px 24px' }}>
      {/* 标题 */}
      <div style={{ marginBottom: 24 }}>
        <Title level={3} style={{ margin: 0 }}>
          结算详情 - {projectName || projectCode || '未指定项目'}
        </Title>
      </div>
      
      <Card bordered={false}>
        {/* 页签 */}
        <Tabs type="card" activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab={<span><CheckOutlined />验收</span>} key="acceptance" />
          <TabPane tab={<span><FileTextOutlined />开票</span>} key="invoice" />
          <TabPane tab={<span><MoneyCollectOutlined />回款</span>} key="payment" />
        </Tabs>

        {/* 结算统计卡片 - 根据页签显示不同数据 */}
        {(activeTab === 'acceptance' || activeTab === 'invoice' || activeTab === 'payment') && (
          <div style={{ overflowX: 'auto', marginBottom: 24 }}>
            <div style={{ display: 'flex', minWidth: 'max-content' }}>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="总结算金额"
                    value={stats.amount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
          {activeTab === 'acceptance' && (
            <>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="已验收金额"
                    value={stats.completedAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="待验收金额"
                    value={stats.amount - stats.completedAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '150px' }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="逾期验收"
                    value={stats.overdue}
                    suffix="条"
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                    prefix={<CloseCircleOutlined />}
                  />
                </Card>
              </div>
            </>
          )}
          {activeTab === 'invoice' && (
            <>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="已开票金额"
                    value={stats.completedAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="待开票金额"
                    value={stats.amount - stats.completedAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '150px' }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="已开票/总计"
                    value={`${stats.completed}/${stats.total}`}
                    suffix="条"
                    valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                    prefix={<FileTextOutlined />}
                  />
                </Card>
              </div>
            </>
          )}
          {activeTab === 'payment' && (
            <>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="已回款金额"
                    value={stats.paidAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="待回款金额"
                    value={stats.remainingAmount}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '150px' }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="已回款/总计"
                    value={`${stats.completed}/${stats.total}`}
                    suffix="条"
                    valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                    prefix={<MoneyCollectOutlined />}
                  />
                </Card>
              </div>
            </>
          )}
            </div>
          </div>
        )}

        {(activeTab === 'acceptance' || activeTab === 'invoice' || activeTab === 'payment') && (
          <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
            <Descriptions.Item label="项目ID">{projectId}</Descriptions.Item>
            <Descriptions.Item label="项目名称">{settlements[0]?.projectName || projectName}</Descriptions.Item>
            <Descriptions.Item label="总结算金额">
              <Text strong>
                ¥{settlements.reduce((sum, s) => sum + (s.budgetAmount || s.acceptanceAmount || 0), 0).toLocaleString()}
              </Text>
            </Descriptions.Item>
          {activeTab === 'acceptance' && (
            <>
              <Descriptions.Item label="已验收金额">
                <Text type="success">
                  ¥{stats.completedAmount.toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="待验收金额">
                <Text type="danger">
                  ¥{(stats.amount - stats.completedAmount).toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="逾期验收">
                <Text type="danger">{stats.overdue}条</Text>
              </Descriptions.Item>
              <Descriptions.Item label="验收状态">
                <Badge 
                  status={stats.pending > 0 ? 'warning' : 'success'} 
                  text={stats.pending > 0 ? '部分验收' : '全部验收'} 
                />
              </Descriptions.Item>
              <Descriptions.Item label="总工时">
                <Text strong>
                  {settlements.reduce((sum, s) => sum + (s.totalHours || 0), 0).toFixed(2)} 小时
                </Text>
              </Descriptions.Item>
            </>
          )}
          {activeTab === 'invoice' && (
            <>
              <Descriptions.Item label="已开票金额">
                <Text type="success">
                  ¥{stats.completedAmount.toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="待开票金额">
                <Text type="danger">
                  ¥{(stats.amount - stats.completedAmount).toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="开票状态">
                <Badge 
                  status={stats.pending > 0 ? 'warning' : 'success'} 
                  text={stats.pending > 0 ? '部分开票' : '全部开票'} 
                />
              </Descriptions.Item>
            </>
          )}
          {activeTab === 'payment' && (
            <>
              <Descriptions.Item label="已回款金额">
                <Text type="success">
                  ¥{stats.paidAmount.toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="待回款金额">
                <Text type="danger">
                  ¥{stats.remainingAmount.toLocaleString()}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="回款状态">
                <Badge 
                  status={
                    stats.pending > 0 && stats.completed > 0 ? 'processing' : 
                    stats.pending > 0 ? 'warning' : 'success'
                  } 
                  text={
                    stats.pending > 0 && stats.completed > 0 ? '部分回款' : 
                    stats.pending > 0 ? '待回款' : '全部回款'
                  } 
                />
              </Descriptions.Item>
            </>
          )}
          </Descriptions>
        )}

        {(activeTab === 'acceptance' || activeTab === 'invoice' || activeTab === 'payment') && (
          <Row justify="space-between" style={{ marginBottom: 16 }}>
            <Col>
              <Input
                placeholder="搜索结算记录"
                prefix={<SearchOutlined />}
                style={{ width: 250 }}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />
            </Col>
          </Row>
        )}

        {activeTab === 'acceptance' && (
          <>
            <Tabs 
              activeKey={activeAcceptanceStatus} 
              onChange={setActiveAcceptanceStatus}
              style={{ marginBottom: 16 }}
              size="small"
            >
              <TabPane tab={`全部 (${settlements.length})`} key="all" />
              <TabPane tab={`待验收 (${settlements.filter(s => s.acceptanceStatus === 'not_accepted').length})`} key="not_accepted" />
              <TabPane tab={`已验收 (${settlements.filter(s => s.acceptanceStatus === 'accepted').length})`} key="accepted" />
            </Tabs>
            <Spin spinning={loading}>
              <Table
                columns={acceptanceColumns}
                dataSource={filteredSettlements}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                scroll={{ x: 2000 }}
                bordered
              />
            </Spin>
          </>
        )}

        {activeTab === 'invoice' && (
          <InvoiceTab 
            projectId={projectId}
            projectCode={projectCode}
            settlements={filteredSettlements} 
            onInvoice={(record) => {
              setCurrentRecord(record);
              setFileList([]);
            }}
            onViewContract={viewContract}
          />
        )}

        {activeTab === 'payment' && (
          <PaymentTab 
            projectId={projectId}
            projectCode={projectCode}
            settlements={filteredSettlements} 
            onPayment={(record) => {
              setCurrentRecord(record);
              setFileList([]);
            }}
            onViewContract={viewContract}
          />
        )}


        {/* 验收模态框 */}
        <Modal
          title={currentRecord?.acceptanceStatus === 'accepted' ? "验收详情" : "项目验收"}
          visible={acceptanceVisible}
          onOk={submitAcceptance}
          onCancel={() => {
            setAcceptanceVisible(false);
            form.resetFields();
            setFileList([]);
          }}
          width={800}
          okButtonProps={{
            disabled: currentRecord?.acceptanceStatus === 'accepted' || acceptanceMembers.some(member => !member.actualHours)
          }}
        >
          <Descriptions bordered column={2} style={{ marginBottom: 16 }}>
            <Descriptions.Item label="项目名称">{currentRecord?.projectName}</Descriptions.Item>
            <Descriptions.Item label="子项目名称">{currentRecord?.subProjectName}</Descriptions.Item>
            <Descriptions.Item label="预算金额">
              <Text strong>¥{currentRecord?.budgetAmount?.toLocaleString()}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="实际结束时间">
              <DatePicker 
                value={actualEndDate ? moment(actualEndDate) : null}
                onChange={(date, dateString) => setActualEndDate(dateString)}
                disabled={currentRecord?.acceptanceStatus === 'accepted'}
                style={{ width: '100%' }}
              />
            </Descriptions.Item>
          </Descriptions>

          <Form
            form={form}
            layout="vertical"
          >
            <Form.Item label="单价类型">
              <Select
                value={priceType}
                onChange={handlePriceTypeChange}
                disabled={currentRecord?.acceptanceStatus === 'accepted'}
                style={{ width: '100%' }}
              >
                {priceTypeOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Row gutter={16} style={{ marginBottom: 16 }}>
              <Col span={12}>
                <Card size="small" title="实际总工时">
                  <Text strong type="success" style={{ fontSize: 18 }}>
                    {acceptanceMembers?.reduce((sum, member) => sum + (member.actualHours || 0), 0)}
                  </Text>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="结算总金额">
                  <Text strong type="danger" style={{ fontSize: 18 }}>
                    ¥{acceptanceMembers?.reduce((sum, member) => sum + (member.settlementAmount || 0), 0).toLocaleString()}
                  </Text>
                </Card>
              </Col>
            </Row>

            <Divider>验收成员列表</Divider>

            <Spin spinning={loadingMembers}>
              <Table
                columns={[
                  {
                    title: '员工姓名',
                    dataIndex: 'employeeName',
                    key: 'employeeName',
                    render: (text, record) => (
                      <Select
                        showSearch
                        value={record.employeeId}
                        onChange={(value) => handleEmployeeChange(record.id, value)}
                        onSearch={handleEmployeeSearch}
                        disabled={currentRecord?.acceptanceStatus === 'accepted'}
                        style={{ width: '100%' }}
                        loading={loadingEmployees}
                        placeholder="搜索员工"
                        filterOption={false}
                        notFoundContent={loadingEmployees ? '搜索中...' : '请输入员工姓名或编号'}
                      >
                        {(employeeSearchResults.length > 0 ? employeeSearchResults : employees).map(emp => (
                          <Option key={emp.id} value={emp.id}>
                            {emp.name} {emp.employeeCode ? `(${emp.employeeCode})` : ''}
                          </Option>
                        ))}
                      </Select>
                    )
                  },
                  {
                    title: '员工编号',
                    dataIndex: 'employeeCode',
                    key: 'employeeCode'
                  },
                  {
                    title: '职位',
                    dataIndex: 'jobTitle',
                    key: 'jobTitle'
                  },
                  {
                    title: '单价',
                    dataIndex: 'unitPrice',
                    key: 'unitPrice',
                    render: (price) => `¥${price?.toLocaleString() || '-'}`
                  },
                  {
                    title: '单价类型',
                    dataIndex: 'priceType',
                    key: 'priceType',
                    render: (type) => priceTypeOptions.find(opt => opt.value === type)?.label
                  },
                  {
                    title: '实际工时',
                    dataIndex: 'actualHours',
                    key: 'actualHours',
                    render: (hours, record) => (
                      <InputNumber 
                        min={0}
                        value={hours}
                        onChange={(value) => handleActualHoursChange(record.id, value)}
                        disabled={currentRecord?.acceptanceStatus === 'accepted'}
                        style={{ width: '100%' }}
                      />
                    )
                  },
                  {
                    title: '结算金额',
                    dataIndex: 'settlementAmount',
                    key: 'settlementAmount',
                    render: (amount) => <Text strong>¥{amount?.toLocaleString() || '-'}</Text>
                  },
                  {
                    title: '操作',
                    key: 'action',
                    width: 150,
                    render: (_, record) => (
                      <Space>
                        <Popconfirm
                          title="确认转项"
                          description="确定要将此成员转到其他项目吗？"
                          onConfirm={() => handleTransferProject(record)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button 
                            type="link" 
                            size="small" 
                            icon={<SwapOutlined />}
                            disabled={currentRecord?.acceptanceStatus === 'accepted'}
                          >
                            转项
                          </Button>
                        </Popconfirm>
                        <Popconfirm
                          title="确认离项"
                          description="确定要为此成员申请离项吗？"
                          onConfirm={() => handleLeaveProject(record)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button 
                            type="link" 
                            size="small" 
                            danger
                            icon={<UserDeleteOutlined />}
                            disabled={currentRecord?.acceptanceStatus === 'accepted'}
                          >
                            离项
                          </Button>
                        </Popconfirm>
                      </Space>
                    )
                  }
                ]}
                dataSource={acceptanceMembers}
                rowKey="id"
                pagination={false}
                bordered
                summary={() => {
                  const totalHours = acceptanceMembers.reduce((sum, member) => sum + (member.actualHours || 0), 0);
                  const totalAmount = acceptanceMembers.reduce((sum, member) => sum + (member.settlementAmount || 0), 0);
                }}
              />
            </Spin>

            <Form.Item label="验收附件" style={{ marginTop: 16 }}>
              <Upload
                fileList={fileList}
                onChange={handleUploadChange}
                beforeUpload={() => false}
              >
                <Button icon={<UploadOutlined />}>上传附件</Button>
              </Upload>
            </Form.Item>
            <Form.Item
              name="note"
              label="备注"
            >
              <Input.TextArea rows={3} />
            </Form.Item>
          </Form>
        </Modal>

        {/* 合同详情模态框 */}
        <Modal
          title={`合同详情 - ${currentRecord?.contractNo}`}
          visible={contractVisible}
          onCancel={() => setContractVisible(false)}
          footer={null}
          width={800}
        >
          <Descriptions bordered column={2}>
            <Descriptions.Item label="合同编号">{currentRecord?.contractNo}</Descriptions.Item>
            <Descriptions.Item label="项目名称">{currentRecord?.projectName}</Descriptions.Item>
            <Descriptions.Item label="子项目名称">{currentRecord?.subProjectName}</Descriptions.Item>
            <Descriptions.Item label="对接人">{currentRecord?.contactPerson}</Descriptions.Item>
            <Descriptions.Item label="客户">{currentRecord?.client}</Descriptions.Item>
            <Descriptions.Item label="部门">{currentRecord?.department}</Descriptions.Item>
            <Descriptions.Item label="科室">{currentRecord?.section}</Descriptions.Item>
            <Descriptions.Item label="预算金额">
              <Text strong>¥{currentRecord?.budgetAmount?.toLocaleString()}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="开始时间">{currentRecord?.startDate}</Descriptions.Item>
            <Descriptions.Item label="预计结束时间">{currentRecord?.estimatedEndDate}</Descriptions.Item>
            <Descriptions.Item label="实际结束时间">{currentRecord?.actualEndDate || '-'}</Descriptions.Item>
            <Descriptions.Item label="预计工时">{currentRecord?.estimatedHours}</Descriptions.Item>
            <Descriptions.Item label="实际工时">{currentRecord?.actualHours || '-'}</Descriptions.Item>
          </Descriptions>
        </Modal>

        {/* 转项模态框 */}
        <Modal
          title="成员转项"
          visible={transferVisible}
          onOk={submitTransfer}
          onCancel={() => {
            setTransferVisible(false);
            transferForm.resetFields();
          }}
          width={600}
        >
          <Form form={transferForm} layout="vertical">
            <Form.Item
              label="项目编号"
              name="projectCode"
              rules={[{ required: true, message: '请选择项目编号' }]}
            >
              <Select
                placeholder="请选择项目编号"
                onChange={handleProjectCodeChange}
                showSearch
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {projectCards.map(card => (
                  <Option key={card.projectCode} value={card.projectCode}>
                    {card.projectCode} - {card.projectName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            
            <Form.Item
              label="子项目名称"
              name="subProjectId"
              rules={[{ required: true, message: '请选择子项目' }]}
            >
              <Select
                placeholder="请先选择项目编号"
                disabled={!transferProjectCode}
              >
                {transferSubProjects.map(subProject => (
                  <Option key={subProject.id} value={subProject.id}>
                    {subProject.projectSubname}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default ProjectSettlementForm;